package com.xunk.equipment.job;

import com.xunk.common.core.enums.SupplierEnum;
import com.xunk.common.core.text.Convert;
import com.xunk.common.redis.service.RedisService;
import com.xunk.equipment.mapper.EquipmentMapper;
import com.xunk.equipment.service.zhijia.constant.ZhijiaConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: HIM
 * @Package: com.xunk.equipment.job
 * @ClassName: ZhijiaDeviceCacheJob
 * @Author: luanzhiwei
 * @Description: 智家设备缓存定时任务
 * @Date: 2021/7/16 9:27
 * @Version: 1.0
 */
@Component
@Slf4j
@EnableScheduling
public class ZhijiaDeviceCacheJob implements ApplicationRunner {

    @Autowired
    private RedisService redisService;
    @Autowired
    private EquipmentMapper equipmentMapper;

    @Scheduled(cron = "* 0/5 * * * ?")
//    @Async
    protected void cacheZhijiaDeviceSn() {
        try {
            cacheDevice();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private void cacheDevice() {
        final List<Map> list = equipmentMapper.selectDeviceSnAndDeptIdBySupplier(SupplierEnum.UPLUS.getSupplierName());
        final Map<String, String> cacheMap = new HashMap<>();
        for (Map item : list) {
            cacheMap.put(Convert.toStr(item.get("deviceSn")), Convert.toStr(item.get("deptId")).concat(":").concat(Convert.toStr(item.get("homeId"))));
        }
        redisService.setCacheMap(ZhijiaConstant.DEVICE_SN_DEPT_ID_HOME_ID, cacheMap);
        redisService.expire(ZhijiaConstant.DEVICE_SN_DEPT_ID_HOME_ID, 5, TimeUnit.MINUTES);
    }

    /**
     * Callback used to run the bean.
     *
     * @param args incoming application arguments
     * @throws Exception on error
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("项目启动，加载智家设备号，deptid，homeid到redis中");
        cacheZhijiaDeviceSn();
    }
}
